(ns scripts.cljmon.json
  (:require clojure.data.json
            clojure.walk))

(defn format-records [data]
  (clojure.data.json/write-str data))

(defn format-headers [fields]
  (clojure.data.json/write-str {:headers fields}))

(defn format-comments [comments]
  (clojure.data.json/write-str {:comment comments}))


(defn- parse-json [lines]
  (->> lines
    (map clojure.data.json/read-str)
    clojure.walk/keywordize-keys))

(defn parse-comments [lines]
  (->> lines
    parse-json
    (take-while :comment)
    (map :comment)
    (remove #(.isEmpty %))))

(defn parse-records [lines]
  (let [jsons (parse-json lines)
        [heading & records] (drop-while :comment jsons)
        named-records (for [json records] (into {} (for [field (:data json)] [(:label field) (str (:value field))])))
        headers (:headers heading)
        records (map (fn [r] (map #(get r %) headers)) named-records)
        columns (map list headers (range))]
    {:headers headers
     :records records
     :named-records named-records
     :columns columns}))
